package com.sansecy.pathmeasure.alipayview;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

public class AliPayView extends View {

    private Paint mPaint;
    private Path mCirclePath;
    private int mCenterX = 300;
    private int mCenterY= 300;
    private int mRadius = 300;
    private Path mDstPath;
    private float mCurAnimValue;
    private PathMeasure mPathMeasure;

    public AliPayView(Context context) {
        this(context, null);
    }

    public AliPayView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(12);
        mPaint.setColor(Color.BLACK);
        mPaint.setAntiAlias(true);

        mDstPath = new Path();
        mCirclePath = new Path();
        mCirclePath.addCircle(mCenterX, mCenterY, mRadius, Path.Direction.CW);

        //每调用一次moveTo都是另一个形状了
        mCirclePath.moveTo(mCenterX - mRadius / 2, mCenterY);
        mCirclePath.lineTo(mCenterX, mCenterY + mRadius / 2);
        mCirclePath.lineTo(mCenterX + mRadius / 2, mCenterY - mRadius / 3);

        mPathMeasure = new PathMeasure(mCirclePath, false);

        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 2);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mCurAnimValue = (float) animation.getAnimatedValue();
                invalidate();
            }
        });
        valueAnimator.setDuration(4000);
        valueAnimator.start();
    }

    boolean mNext = false;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mCurAnimValue < 1) {
            float stop = mPathMeasure.getLength() * mCurAnimValue;
            mPathMeasure.getSegment(0, stop, mDstPath, true);
        } else {
            if (!mNext) {
                mNext = true;
                mPathMeasure.getSegment(0, mPathMeasure.getLength(), mDstPath, true);
                mPathMeasure.nextContour();
            }
            float stop = mPathMeasure.getLength() * (mCurAnimValue - 1);
            mPathMeasure.getSegment(0, stop, mDstPath, true);
        }

        canvas.drawPath(mDstPath, mPaint);

    }
}
